<?php
class Product_Provider extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
				# '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'product_provider',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	/**
	 * 创建或编辑供应商资料
	 * @param $provider 供应商资料数组，假如id存在则更新，假如id不存在则创建
	 */
	static function createOrEidt($provider)
	{
		$result = Product_Provider::judgeCreateOrEdit($provider);
		if ($result['ack'] == SUCCESS)
		{
			if (isset($provider) && ! empty($provider['id']))
			{
				$provider_to_db = Product_Provider::find('id=?', $provider['id'])->getOne();
			}
			else
			{
				$provider_to_db = new Product_Provider();
				$provider_to_db->create_time = CURRENT_DATETIME;
			}
			$provider_to_db->name = $provider['name'];
			$provider_to_db->follow_user_id = $provider['follow_user_id'];
			$provider_to_db->payment_method = $provider['payment_method'];
			$provider_to_db->pay_deadline = (int)$provider['pay_deadline'];
			$provider_to_db->contact_person = $provider['contact_person'];
			$provider_to_db->qq = $provider['qq'];
			$provider_to_db->fax = $provider['fax'];
			$provider_to_db->email = $provider['email'];
			$provider_to_db->phone = $provider['phone'];
			$provider_to_db->cellphone = $provider['cellphone'];
			$provider_to_db->address = $provider['address'];
			$provider_to_db->type = $provider['type'];
			$provider_to_db->wang_wang = $provider['wang_wang'];
			$provider_to_db->link = $provider['link'];
			$provider_to_db->save();
			if (isset($provider['product_categories_ids']))
			{
				$provider_id = mysql_insert_id() ? mysql_insert_id() : $provider['id'];
				Product_Provider::updateMapping($provider_id, $provider['product_categories_ids']);
			}
			return array('ack' => SUCCESS, 'message' => '', 'provider_id' => $provider_id);
		}
		else
		{
			return array('ack' => $result['ack'], 'message' => $result['message']);
		}
	}
	
	static function judgeCreateOrEdit($provider)
	{
		if ($provider['type'] == Q::ini('custom_flag/product_provider_type/online/value') && ($provider['wang_wang'] == '' || $provider['link'] == ''))
		{
			return array('ack' => FAILURE, 'message' => '旺旺号或店铺链接不能为空');
		}
		if (empty($provider['name']))
		{
			return array('ack' => FAILURE, 'message' => '名称不能为空');
		}
		if (empty($provider['follow_user_id']))
		{
			return array('ack' => FAILURE, 'message' => '跟进人员不能为空');
		}
		if (empty($provider['contact_person']))
		{
			return array('ack' => FAILURE, 'message' => '联系人不能为空');
		}
		if (empty($provider['phone']))
		{
			return array('ack' => FAILURE, 'message' => '电话不能为空');
		}
		if (empty($provider['address']))
		{
			return array('ack' => FAILURE, 'message' => '通讯地址不能为空');
		}
		if (empty($provider['type']))
		{
			return array('ack' => FAILURE, 'message' => '供应商类型不能为空');
		}
		if (isset($provider['product_categories_ids']))
		{
			if (isset($provider['id']) && $provider['id'])
			{
				$provider_to_db = Product_Provider::find('id=?', $provider['id'])->getOne();
				if ( ! $provider_to_db['id'])
				{
					return array('ack' => FAILURE, 'message' => '供应商ID不存在系统');
				}
			}
			return array('ack' => SUCCESS, 'message' => '');
			
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '产品分类不能为空!');
		}
	}
	
	static function updateMapping($provider_id, $product_categories_ids)
	{
		$old_mapping = array();
		$mapping = QDB::getConn()->execute('select * from provider_categories_mapping where product_provider_id=' . $provider_id)->fetchAll();
		foreach ($mapping as $m)
		{
			$old_mapping[] = $m['product_categories_id'];
		}
		$mapping_create = array_diff($product_categories_ids, $old_mapping);
		$mapping_delete = array_diff($old_mapping, $product_categories_ids);
		foreach ($mapping_create as $mc)
		{
			QDB::getConn()->execute('insert into provider_categories_mapping values(' . $provider_id . ', ' . $mc . ')');
		}
		foreach ($mapping_delete as $md)
		{
			QDB::getConn()->execute('delete from provider_categories_mapping where product_provider_id=' . $provider_id . ' and product_categories_id=' . $md);
		}
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	/**
	 * 获取当前用户ID有权限管理的分类ids
	 */
	static function getMapping()
	{
		$user_group = User::getOffspringById(CURRENT_USER_ID, 'id');
		array_push($user_group, CURRENT_USER_ID);
		$has_categories_ids = QDB::getConn()->execute('select distinct(provider_categories_mapping.product_categories_id) from provider_categories_mapping join product_provider on product_provider.id=provider_categories_mapping.product_provider_id where product_provider.follow_user_id in (' . implode(',', $user_group) . ')')->fetchCol();
		$mapping_ids = $has_categories_ids;
		foreach ($has_categories_ids as $hci)
		{
			$categories = Product_Categories::find('id=?', $hci)->asArray()->getOne();
			if ($categories)
			{
				$mapping_ids = array_merge($mapping_ids, Product_Categories::getOffspringById($hci));
				if (!in_array($categories['parent_id'], $mapping_ids))
				{
					$mppping_ids = array_push($mapping_ids, $categories['parent_id']);
				}
			}
		}
		return $mapping_ids;
	}
	
	static function search($condition, $cp, $ps)
	{
		$columns = array(
			'product_provider.*',
			'user.name as follow_user_name, user.status as user_status'
		);
		$where = Product_Provider::buildSearchWhere($condition);
		if ($cp == 0 && $ps == 0)
		{
			$select = Product_Provider::find($where)
				->joinLeft('user', '', 'user.id=product_provider.follow_user_id');
			if (! empty($condition['product_categories_id']))
			{
				$select->joinLeft('provider_categories_mapping', '', 'provider_categories_mapping.product_provider_id=product_provider.id');
			}
			$select->setColumns($columns)->order('product_provider.id desc');
			$pagination = array();
		}
		else
		{
			$select = Product_Provider::find($where)
				->joinLeft('user', '', 'user.id=product_provider.follow_user_id');
			if (! empty($condition['product_categories_id']))
			{
				$select->joinLeft('provider_categories_mapping', '', 'provider_categories_mapping.product_provider_id=product_provider.id');
			}
			$select->setColumns($columns)->order('product_provider.id desc')->limitPage($cp, $ps);
			$pagination = $select->getPagination();
		}
		$provider = $select->asArray()->getAll();
		return array(
			'ack' => SUCCESS,
			'message' => '',
			'data' => $provider,
			'pagination' => $pagination
		);
		
	}
	
	static function buildSearchWhere($condition)
	{
		$where = '1';
		if (! empty($condition['status']))
		{
			$status = '0';
			foreach ($condition['status'] as $c)
			{
				if ($c == '')
				{
					$status .= ' or product_provider.follow_user_id=\'\'';
					continue;
				}
				$status .= ' or user.status=' . $c;
			}
			$where .= ' and (' . $status . ')'; 
		}
		if ( ! empty($condition['product_categories_id']))
		{
			$product_categories_ids = Product_Categories::getOffspringById($condition['product_categories_id']);
			array_push($product_categories_ids, $condition['product_categories_id']);
			$where .= ' and provider_categories_mapping.product_categories_id in (' . implode(',', $product_categories_ids) . ')';
		}
		if (isset($condition['limit']) && $condition['limit'])
		{
			$where .= ' and product_provider.follow_user_id=' . CURRENT_USER_ID;
		}
		if ( ! empty($condition['ids']))
		{
			$where .= ' and product_provider.id in (' . implode(',', $condition['ids']) . ')';
		}
		if ( ! empty($condition['id']))
		{
			$where .= ' and product_provider.id=\'' . $condition['id'] . '\'';
		}
		if ( ! empty($condition['ajax_provider']))
		{
			$actual_provider_id = explode(' ', $condition['ajax_provider']);
			$where .= ' and product_provider.id=\'' . $actual_provider_id[0] . '\'';
		}
		if ( ! empty($condition['name']))
		{
			$where .= ' and product_provider.name like \'%' . $condition['name'] . '%\'';
		}
		if ( ! empty($condition['address']))
		{
			$where .= ' and product_provider.address like \'%' . $condition['address'] . '%\'';
		}
		if ( ! empty($condition['contact_person']))
		{
			$where .= ' and product_provider.contact_person like \'%' . $condition['contact_person'] . '%\'';
		}
		if ( ! empty($condition['phone']))
		{
			$where .= ' and product_provider.phone like \'%' . $condition['phone'] . '%\'';
		}
		if ( ! empty($condition['follow_user_id']))
		{
			$where .= ' and product_provider.follow_user_id=\'' . $condition['follow_user_id'] . '\'';
		}
		if ( ! empty($condition['type']))
		{
			$where .= ' and product_provider.type=\'' . $condition['type'] . '\'';
		}
		if ( ! empty($condition['wang_wang']))
		{
			$where .= ' and product_provider.wang_wang=\'' . $condition['wang_wang'] . '\'';
		}
		if ( ! empty($condition['link']))
		{
			$where .= ' and product_provider.link=\'' . $condition['link'] . '\'';
		}
		return $where;
	}
}



